package com.netease.nie.controllers;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.netease.nie.base.cache.redis.RedisManager;
import com.netease.nie.base.controllers.BaseController;
import com.netease.nie.base.exceptions.UnexpectedException;
import com.netease.nie.base.utils.CustomWebUtils;
import com.netease.nie.constants.CachePrefixConstants;
import com.netease.nie.dto.LoginLogoutDto;
import com.netease.nie.dto.UserLoginDto;
import com.netease.nie.model.Credit;
import com.netease.nie.service.CreditService;
import com.netease.nie.utils.LogUtils;
import com.netease.nie.utils.UserLoginUtils;

/**
 * 用户登出
 * @author wwbn3695
 * @createDate August 30th,2016
 *
 */
@RestController
@RequestMapping("/api/logout")
public class UserLogoutController extends BaseController {
	
	@Autowired
	private CreditService creditService;
	
	private Logger logger = Logger.getLogger(UserLoginController.class);

	private static final String USER_TOKEN_PREFIX = CachePrefixConstants.UserPrefix.USER_TOKEN_PREFIX;

	@RequestMapping(value = "/normal", method = RequestMethod.POST, produces = "application/json")
	public String logout(HttpServletRequest request, HttpServletResponse response) throws Exception {
		final UserLoginDto userLoginDto = UserLoginUtils.getUserLoginDto(request);
		if (userLoginDto == null)
			throw new UnexpectedException("用户未登录");
		
		String userToken = UserLoginUtils.generateUserToken(userLoginDto);
		logger.info("userToken = " + userToken);
		String userTokenKey = USER_TOKEN_PREFIX + userToken;
		RedisManager redisManager = new RedisManager();
		redisManager.del(userTokenKey);
		UserLoginUtils.deleteNeteaseMobileCookie(request, response);
		
		/**
		 * 登出日志
		 */
		Long userId = (Long) request.getAttribute("userId");
		if (userId != null) {
			Credit credit = creditService.queryUserCreditByUserId(userId);
			LoginLogoutDto loginLogoutDto = new LoginLogoutDto();
//			loginLogoutDto.setAccountId(userLoginDto.getSsn());
			loginLogoutDto.setUserId(String.valueOf(userId));
			loginLogoutDto.setAccountVip(credit.getLevel());
			loginLogoutDto.setLeftPoint(credit.getCurrentCredit());
			loginLogoutDto.setExpirePoint(credit.getReadyToExpireCredit());
			loginLogoutDto.setIp(CustomWebUtils.getIp(request));
			
			LogUtils.logLogout(loginLogoutDto);
		}
		
		return jsonSuccess(1);
	}
}
